import random
from functools import reduce
from math import sqrt
import time

# # 练习1：
# # 写出下列题目的输出分别是什么。
# （1）
# name1 = "candy"
# name2 = "candy"
# print name1 == name2
# print name1 is name2
#
# 输出：
# True
# True
#
# list1 = [1,2,3]
# list2 = [1,2,3]
# print list1 == list2
# print list1 is list2
#
# 输出：
# True
# Flase
#
#
# （2）
# age = 10
# if age < 3:
#     print "婴幼儿"
# elif age >= 3 and age < 12:
#     print "儿童"
# elif age >= 12 and age < 28:
#     print "青少年"
# else:
#     print "输入年龄不合法"
#
# 输出结果：儿童
#
# （3）
# a = 21
# b = 10
#
# print a / b
# print a / float(b)
# print a % b
# 输出：
# 2.1
# 2.1
# 1
#
# a = 11
# b = 3
# c = a//b
#
# print a//b
# print a//float(b)
#
# 输出：
# 3
# 3.0
#
# a = -11
# b = 3
# print a//b
#
# 输出：
# -4
# # 联系2：根据用户输入的数字判断是奇数还是偶数
# a=input('请输入一个数字：')
# if a.strip().isdigit() or  a.startswith('-') and a[1:].isdigit():
#     a=int(a)
#     if a%2==0:
#         print('%s为偶数'%a)
#     else:
#         print('%s为奇数'%a)
# else:
#     print('请输入纯数字')
# #3.接收用户输入一个年份，判断是否是闰年(判断闰年的方法是该年能被4整除并且不能被100整除，或者是可以被400整除)
# year=input('请输入一个年份')
# if year.strip().isdigit():
#     year=int(year)
#     if year>0:
#         if year%4==0 and year%100!=0:
#             print('%s年为闰年'%year)
#         elif year%400==0:
#             print('%s年为闰年'%year)
#         else:
#             print('%s年不为闰年'%year)
#     else:
#         print('输入年份不能为0')
# elif year.startswith('-') and year[1:].isdigit():
#     print('输入年份不能为负数')
# # 练习4：根据指定的月份打印该月份所属的季节
# month=input('请输入一个月份')
# if month.strip().isdigit() :
#     month=int(month)
#     if month>0 and month<=12:
#         if month in (12,1,2):
#             print('%s为冬天'%month)
#         elif month in (3,4,5):
#             print('%s为春天'%month)
#         elif month in (6,7,8):
#             print('%s为夏天'%month)
#         else:
#             print('%s为秋天'%month)
#     else:
#         print('输入月份应该在1-12月范围内')
# else:
#     print('输入月份不正确')
# #练习5：根据用户输入的狗狗的年龄得出相当于人的多少岁,假设：狗狗的前2年，一年相当 于人的10.5岁；往后每一年相当于4岁计算
# dog_age=input('请输入狗狗年龄')
# if dog_age.strip().isdigit():
#     dog_age=int(dog_age)
#     if dog_age > 0 and dog_age<=2:
#        men_age=dog_age*10.5
#        print('人年龄为%s' % men_age)
#     elif dog_age>2 and dog_age<=20:
#         men_age=(10.5*2)+(dog_age-2)*4
#         print('人年龄为%s' % men_age)
#     else:
#         print('输入狗狗年龄应该在1-20之间')
# else:
#     print('输入狗狗年龄非正整数')
#
# #练习6：求1000以内所有的水仙花数
# for i in range(100,1000):
#     if (i%10)**3+(i//10%10)**3+(i//100)**3==i:
#         print(i)
#字符串切割，转整数计算判断
# for i in range(100,1000):
#     i=str(i)
#     if int(i[0])**3+int(i[1])**3+int(i[2])**3==int(i):
#         print(i)

# #练习7：重复接受用户输入的一个字符串，如果是正整数, 就输出结果，否则一直输入
# while True:
#     a=input('请输入一个字符串')
#     if a.strip().isdigit() and not a.startswith('-'):
#         print(a)
#         break
#     else:
#         continue
#
# #练习8：需求：猜数字（10以内），猜对了结束，猜不对继续
# while True:
#     a=input('请输入一个字符串')
#     if a.strip().isdigit():
#         a=int(a)
#         if a<=10:
#             print(a)
#             break
#     else:
#         continue
#
# #练习9：打印出1-100之间的所有偶数（两种解法）
# for n in range(2,101,2):
#     print(n)
# for n in range(2,101):
#     if n %2==0:
#         print(n)
# i=1
# while i<=100:
#     if i%2==0:
#         print(i)
#     i+=1


# #练习 10：求1到10之间的累加，累乘（1到10的阶乘）扩展：两种循环求解、1到N
# sum=0
# for n in range(1,11):
#    sum+=n
# print(sum)
#
# scend=1
# for n in range(1,11):
#     scend*=n
# print(scend)
#
# #练习11. 求100以内的质数,质数是指在大于1的自然数中，除了1和它本身以外不再有其他因数的自然数

# for i in range(2,101):
#     for j in range(2,i):
#          if i%j==0:
#             break
#     else:
#         print(f'{i}为质数')


# # 练习12 ：企业发放的奖金根据利润提成
# # 利润(I)低于或等于10万元时，奖金可提10%；
# # 利润高于10万元，低于20万元时，低于10万元的部分按10%提成，高于10万元的部分，可可提成7.5%；
# # 20万到40万之间时，高于20万元的部分，可提成5%；
# # 40万到60万之间时高于40万元的部分，可提成3%；
# # 60万到100万之间时，高于60万元的部分，可提成1.5%，
# # 高于100万元时，超过100万元的部分按1%提成，
# # 从键盘输入当月利润I，求应发放奖金总数？
# money=0
# profit=input('请输入利润值，单位万：')
# if profit.strip().isdigit():
#     profit=int(profit)
#     if profit<=10:
#         money=10*10/100
#         print('可提奖金为%s万元'%money)
#     elif profit>10 and profit<20:
#         money=(profit-10)*7.5/100+10*10/100
#         print('可提奖金为%s万元' % money)
#     elif profit>=20 and profit<40:
#         money=(profit-20)*5/100+(profit-10)*7.5/100+10*10/100
#         print('可提奖金为%s万元' % money)
#     elif profit>=40 and profit<60:
#         money = (profit-40)*3/100+(profit-20)*5/100+(profit-10)*7.5/100+10*10/100
#         print('可提奖金为%s万元' % money)
#     elif profit>=60 and profit<100:
#         money+=(profit-60)*1.5/100+(profit-40)*3/100+(profit-20)*5/100+(profit-10)*7.5/100+10*10/100
#         print('可提奖金为%s万元' % money)
#     else:
#         money+=(profit-100)*1/100+(profit-60)*1.5/100+(profit-40)*3/100+(profit-20)*5/100+(profit-10)*7.5/100+10*10/100
#         print('可提奖金为%s万元' % money)
# else:
#     print('请输入正确的利润值')

#练习13 ：输入一行字符，分别统计出其中英文字母、空格、数字和其它字符的个数
# alpha=0
# space=0
# shuzi=0
# other=0
# str=input('请输入一个字符串：')
# for i in str:
#     if i.isalpha():
#         alpha+=1
#     elif i.isspace():
#         space+=1
#     elif i.isdigit():
#         shuzi+=1
#     else:
#         other+=1
# print(f'输入字符中共有字母{alpha}个，空格{space}，数字{shuzi}，其他字符{other}')

# 练习14 ：给定一个字符串，找出其中第几位是数字
seq = '2Apples&3Pears&5bananas'
for i in range(0,len(seq)):
    if seq[i].isdigit():
        print(i,seq[i])

# 练习15 ：打印一个9*9 的方阵，由星号组成
# for i in range(1,10):
#     for j in range(1,10):
#         print('*' ,end='')
#     print()

# *练习16 ：接收用户输入的一个字符串：h, w 代表矩形的高和宽，打印一个空心的矩形
# h=int(input('请输入矩形高'))
# w=int(input('请输入矩形宽：'))
# for i in range(0,h):
#     for j in range(0,w):
#         if i==0 or i==h-1 or j==0 or j==w-1:
#             print('*',end=' ')
#         else:
#             print(' ',end=' ')
#
#     print('')

# 实心矩形
# h=int(input('请输入矩形高'))
# w=int(input('请输入矩形宽：'))
# for i in range(0,h):
#     for j in range(0,w):
#         print('*',end='')
#     print('')

# #练习17 ：找1000以内最大平方数
# for i in range(1000,0,-1):
#     if i*i<=1000:
#         print(i*i)
#         break
# for i in range(1000,0,-1):
#     if sqrt(i)==float(int(sqrt(i))):
#         print(i)
#         break

# 练习18 ：给定一个字符串 target = 'hi liulaoshi，从中找出第一个不重复的字符,输出它是第几位
# target = 'hi liulaoshi'
# for i in range(0,len(target)):
#     if target.count(target[i])==1 and  target[i]!=' ':
#         print(target[i],i)
#         break
# 练习19 ：一个5位数，判断它是不是回文数。即12321是回文数，个位与万位相同，十位与千位相同

# for i in range(10000,100000):
#     i=str(i)
#     if i[-1]==i[0]and i[-2]==i[1]:
#         print(i)


# 练习20 ：一个数如果恰好等于它的因子之和，这个数就称为“完数”。例如6=1＋2＋3.编程找出1000以内的所有完数

# for i in range(1,1001):
#     sum = 0
#     for j in range(1,i):
#         if i%j==0:
#             sum+=j
#     if sum==i:
#         print(i)
#练习21：输入两个字符串，从第一个字符串中删除第二个字符串中的所有字符。例如：输入”They are Students”和”aeiou”，删除之后第一个字符串变为 ‘Thy r stdnts’
# a='They are Students'
# b='aeiou'
# for i in b:
#     for j in a:
#         if j==i:
#             a=a.replace(j,'')
# print(a)


#练习22--使用方法for--else如果for循环都执行完毕，执行else语句，反之不执行else：

# str=input('请输入一个字符串:')
# if  str.isalpha() and str.isupper() and len(str)<=100:
#     for i in range(0,len(str)-1):
#         if   str[i]==str[i+1]:
#             print('dislike')
#             break
#     else:
#         print('like')
# else:
#     print('dislike')

#练习23按字符串原有字符顺序输出字符合集
# str=input('请输入一个字符串:')
# if  str.encode().isalpha()  and len(str)<=100:
#     a=''
#     for i in str:
#         if i not in a:
#             a+=i
#     print(a)
# else:
#     print('输入不合法')




#练习24： 字符串a = "not 404 found 张三 99 深圳"，每个词中间是空格，滤掉英文和数字，最终输出"张三  深圳"
# a = "not 404 found 张三 99 深圳"
# for i in (a.split(' ')):
#     if   i.isdigit() or i.encode().isalpha():
#         a=a.replace(i,'')
# print(a)
#转16进制编码，中文不符合字符判断条件
# a = "not 404 found 张三 99 深圳"
# for i in (a.split(' ')):
#     if   i.encode().isalnum():
#         a=a.replace(i,'')
# print(a)
#练习25：输出九九乘法口诀
# for i in range(1,10):
#     for j in range(1,i+1):
#         print(f'{j}x{i}=%d'%(i*j),end='\t')
#     print('')


#练习26 ：一个整数，它加上100后是一个完全平方数，再加上168又是一个完全平方数，请问该数是多少？
# from math import sqrt
# for a in range(0,10000):
#     if sqrt(a+100)==float(int(sqrt(a+100))) and sqrt(a+268)==float(int(sqrt(a+268))):
#         print(a)
#         break



#练习27： I love China  输出 China love I
# str='I love China'
# for i in str.split(' ')[::-1]:
#     print(i,end=' ')


#练习28
# a=input('请输入一个整数a:')
# b=input('请输入一个整数b:')
# c=input('请输入一个整数c:')
# count=0
# if a.isdigit() and b.isdigit() and c.isdigit():
#     a=int(a)
#     b=int(b)
#     c=int(c)
#     if 0<=a<=b and c>0:
#         for i in range(a,b+1):
#             if i%c==0:
#                 count+=1
#                 print(i)
#         print('a和b之间能给c整除的个数为%d'%count)
#     else:
#         print('输入数据不符合要求')
# else:
#     print('请输入正整数')

# 练习29：
# a=((1, 'zhangsan', 3000), (2, 'lisi', 2500), (3, 'liulaoshi', 20000))
# count=0
# xueba=''
# maxa=0
# for i in range(0,len(a)):
#     if a[i][-1]>maxa:
#         maxa=a[i][-1]
#         xueba=a[i][1]
#     count+=a[i][-1]
# print('员工平均工资为%d'%(count/len(a)))
# print('工资最高的员工姓名为:%s'%(xueba))

# 练习30：
# a=(('技术部', (367, 500, 45)), ('人力资源部', (247, 368, 1280)), ('财务部', (87, 100, 24, 50)))
# count=0
# mina=100000000
# minbumen=''
# for  i in range(0,len(a)):
#     if sum(a[i][-1])<mina:
#         mina=sum(a[i][-1])
#         minbumen=a[i][0]
#     count+=sum(a[i][-1])
# print('公司本月加班费%d'%(count))
# print('公司加班最小的部门%s'%(minbumen))

# 练习31：
# a=( (5, 7) , (18, 20) , (35, 37), (56, 58) )
# b=(6, 15, 47, 57, 86)
# count=0
# for i in b:
#     for j in a:
#         if i in range(j[0],j[1]+1):
#             count+=1
# print(f'b中数字落入a中区间数据为{count}')

# 练习32：
# count=0
# for i in range(1,5):
#     for j in range(1,5):
#         for k in range(1,5):
#             for l in range(1,5):
#                 if i!=j and i!=k and i!=l and j!=k and j!=l and  k!=l:
#                     count+=1
#                     a=i*1000+j*100+k*10+l*1
#                     print(a)
# print(f'数字1、2、3、4能组成互补重复的四位数为{count}个')


# 练习33：
# names = ['fentiao','fendai','fensi','fish']
# a='I have '+','.join(names[0:-1])+' and '+names[-1]
# print(a)

# 练习34：
# products =[["iphone",6888],["MacPro",14800],["小米6",2499],["Coffee",31],["Book",60],["Nike",699]]
# print('------  商品列表 ------')
# for  i in range(0,len(products)):
#     print('%d   %s  %s'%(i,products[i][0],products[i][1]) )


# 练习35：
# products =[["iphone",6888],["MacPro",14800],["小米6",2499],["Coffee",31],["Book",60],["Nike",699]]
# b=[]
# result=[]
# while True:
#     id=input('请输入商品编号：')
#     if id != 'q':
#         id=int(id)
#         b.append(products[id][0])
#     else:
#         for p in products:
#             count=b.count(p[0])
#             money=count*p[1]
#             if count!=0:
#                 result.append('{name}*{count}*{money} '.format(name=p[0], count=count,money=money))
#         break
# print(result)


# 练习36：
#set方式,set去重后，会改变原有列表排列顺序，如果想保持顺序不变，就继续对set后列表按照原有列表index排序
# a = [1,3,12,7,3,1,5,8,12,5,21,44]
# print(sorted(list(set(a)),key=a.index))
#空列表形式：
# a = [1,3,12,7,3,1,5,8,12,5,21,44]
# b=[]
# for i  in a:
#     if i not in b:
#         b.append(i)
# print(b)

#字典：
# a = [1,3,12,7,3,1,5,8,12,5,21,44]
# b={}
# for i in a:
#     b[i]= ''
# print(list(b.keys()))
# # 练习37：
# a=['tom', 'jerry', 'bob', 'mario']
# b=['zhangsan', 'lisi', 'liuneng', 'xieguangkun']
# # a.extend(b)
# # print(a)
#
# print(list(set(a)|set(b)))

# 练习38：

# a = [1,3,4,7,11]
# b=[]
# for i in a:
#     b.append((i+2)**2)
# print(b)
# 练习39：
# title='华为春季新品发布会&sign=323dwd&limit=100&status=0&address=国家会议中心&time=2018-03-28'
# b=title.split('&')
# for i in range(0,len(b)):
#     if b[i].startswith('sign'):
#         b[i]='sign=1234'
# print('&'.join(b))

# 练习40：

# b=[]
# while True:
#     a=input('输入一个数字：')
#     if a.isdigit():
#         a=int(a)
#         b.append(a)
#     elif a.startswith('-') and a[1:].isdigit():
#         break
#     else:
#         print('请输入正确的数字')
# print(max(b),min(b))
# print(sorted(b))


#

# 练习41：
#AB进行合并，去掉重复项
# A = ['北京', '西安', '上海', '成都', '武汉', '郑州', '哈尔滨']
# B = ['郑州', '天津', '成都', '西安']
# A.extend(B)
# print(set(A))
#取并集
# A = ['北京', '西安', '上海', '成都', '武汉', '郑州', '哈尔滨']
# B = ['郑州', '天津', '成都', '西安']
# print(list(set(A)&set(B)))
#取差异集
# A = ['北京', '西安', '上海', '成都', '武汉', '郑州', '哈尔滨']
# B = ['郑州', '天津', '成都', '西安']
# print(list(set(A)^set(B)))
# 练习42：
# result=[]
# n=int(input('请输入调查人数N：'))
# for i in range(0,n):
#     a=random.randint(1,1000)
#     if a not in result:
#         result.append(a)
# print(sorted(result))
# 练习43：
# a=[2, 5, 3, 9, 7, 3, 6, 9, 2]
# b=list(set(a))
# b.sort(key=a.index)
# print(b)
# 练习44:
# count=1
# coount1=0
# b=[]
# a=input('请输入一串英文单词：')
# for i in  a.split(' '):
#     if i not in b:
#         b.append(i)
#         print(a.count(i))
# print(b)

# 练习45:
# nums = [2,7,9,0,1,8,12]
# r=[]
# for i in range(0,len(nums)-1):
#     for j in range(i+1,len(nums)):
#         if nums[i]+nums[j]==9:
#             r.append((nums[i],nums[j]))
# print(r)
# 练习46：
# list1 = [2, 3, 8, 4, 9, 5, 6]
# list2 = [5, 6, 10, 17, 11, 2]
# list1.extend(list2)
# print(sorted(list(set(list1))))
# 练习47：
# users = ['root','westos']
# passwds = ['123','456']
# a=0
# b=0
# while a<3 and b<3:
#     user=input('请输入用户名:')
#     if user in users:
#         passwd=input('请输入密码:')
#         i=users.index(user)
#         if passwds[i]==passwd:
#             break
#         else:
#             continue
#             a+=1
#     else:
#         b+=1
# 练习48：

# random.random--0--1的小数
# random.randint----一个范围内整数
# r={}
#循环一百次生成一百个卡号
# for i in range(1,101):
# #生成一个100-999三位随机数
#     suiji = random.randint(100, 999)
# #如果数字小于10最后三位为00i
#     if i<10:
#         shuzi='00'+str(i)
# #如果数字大于10小于100最后三位为0i
#     elif i>=10 and i<=100:
#         shuzi='0'+str(i)
# #如果数字等于100最后三位为i
#     else:
#         shuzi='100'
# #定义个空字典r，对字典进行赋值字符串拼接
#     r['6102009{suiji}{shuzi}'.format(suiji=suiji,shuzi=shuzi)]='redhat'
# print(r)
#

# 练习49
# address='address=beijing&limit=200&title=XiaoMi_Test&time=2018-01-30&username=liulaoshi'
# b=address.split('&')
# a=[]
# for i in b:
#     if not i.startswith('username='):
#         a.append(i)
# print('token=123456'+'&'.join(sorted(a,reverse=True)))
# 练习50：
# list1=['刘能', '王老七', '谢广坤', '赵玉田', '杨晓燕', '刘大脑袋', '王长贵', '谢飞机', '赵四', '王大拿'][::-1]
# xing,name=[],[]
# for i in list1:
#     if i[0] not in xing:
#         xing.append(i[0])
#         name.append(i)
# name.reverse()
# print(name)

# 练习51：
# a={'刘德华' : 367,  '张学友': 247 ,  '李小璐': 50,'刘老师': 1280}
# b={'技术部' : (367, 500, 45),  '人力资源部': (247, 368, 1280),  '财务部': (87, 100, 24, 50)}
# count=0
# for i in a.values():
#     count+=i
# for i in b.values():
#     count+=sum(i)
# print(count)

# # 练习52：
# list={'刘德华' : 367,  '张学友': 247 ,  '李小璐': 50,'刘老师': 1280,'贾乃亮': 760}
# a=[]
# b=[]
# c={}
# for k,v in list.items():
#     if v<500:
#         a.append(k)
#     else:
#         b.append(k)
# c['报销大于500']=b
# c['报销小于500']=a
# print(c)

# 练习53：
# data = {
#     'ZhaoLiYing': 60,
#     'FengShaoFeng': 75,
#     'ZhangLaoShi': 99,
#     'TangYan': 88,
#     'LuoJin': 35,
#     'LiuLaoShi': 100
# }
# count=0
# maxv=0
# xueba=''
# for  k,v in data.items():
#     count+=v
#     if v>maxv:
#         maxv=v
#         xueba=k
# print('学员平均分为%d'%(count/len(data)))
# print('学员最高分为%d学霸为%s'%(maxv,xueba))

# 练习54：
# data = {
#      'ZhaoLiYing': [60, 68, 45],
#      'FengShaoFeng': [10, 28, 5],
#      'ZhangLaoShi': [44, 86, 73],
#      'TangYan': [99, 95, 95],
#      'LuoJin': [98, 65, 100],
#      'LiuLaoShi': [77, 97, 65]
# 	}
# yuwen,shuxue,yingyu={},{},{}
# maxyuwen,maxshuxue,maxyingyu=0,0,0
# xuebayuwen,xuebashuxue,xuebayingyu='','',''
# for k,v in data.items():
#     yuwen[k],shuxue[k],yingyu[k]=v[0],v[1],v[2]
#     if sum(v)/len(v)<60:
#         print('平均分不足60分的人为%s'%(k))
# for k1,v1 in yuwen.items():
#     if v1>maxyuwen:
#         maxyuwen,xuebayuwen=v1,k1
# for k1, v1 in shuxue.items():
#     if v1 > maxshuxue:
#         maxshuxue,xuebashuxue=v1,k1
# for k1, v1 in yingyu.items():
#     if v1 > maxyingyu:
#         maxyingyu,xuebayingyu=v1,k1
# print(f'语文最高分为{maxyuwen}学霸为{xuebayuwen},数学最高分为{maxshuxue}学霸为{xuebashuxue},英语最高分为{maxyingyu}学霸为{xuebayingyu}')


# 练习55：
# data = {
#     '颖宝':{'语文':60, '数学':68, '英语':45},
#     '冯威':{'语文':10, '数学':28, '英语':5},
#     '糖糖':{'语文':44, '数学':86, '英语':73},
#     '咕噜':{'语文':99, '数学':95, '英语':95},
#     '张老师':{'语文':98, '数学':65, '英语':100},
#     '刘老师':{'语文':77, '数学':97, '英语':65},
# }
# yuwen,shuxue,yingyu={},{},{}
# maxyuwen,maxshuxue,maxyingyu=0,0,0
# xuebayuwen,xuebashuxue,xuebayingyu='','',''
# for k,v in data.items():
#     yuwen[k], shuxue[k], yingyu[k] = v['语文'], v['数学'], v['英语']
#     if sum(list(v.values()))/len(v)<60:
#         print('平均分不足60分的人为%s'%(k))
# for k1,v1 in yuwen.items():
#     if v1>maxyuwen:
#         maxyuwen,xuebayuwen=v1,k1
# for k1, v1 in shuxue.items():
#     if v1 > maxshuxue:
#         maxshuxue,xuebashuxue=v1,k1
# for k1, v1 in yingyu.items():
#     if v1 > maxyingyu:
#         maxyingyu,xuebayingyu=v1,k1
# print(f'语文最高分为{maxyuwen} 学霸为{xuebayuwen},数学最高分为{maxshuxue} 学霸为{xuebashuxue},英语最高分为{maxyingyu} 学霸为{xuebayingyu}')

# # 练习56：
#
a='''a a sample of texts from Project Gutenberg appears in the NLTK corpus collection. However,you may be interested in analyzing other texts from Project Gutenberg. You can browse the catalog
of 25,000 free online books at http://www.gutenberg.org/catalog/,and obtain a URL to an ASCII text file.
Although 90% of the texts in Project Gutenberg are in English,it includes material in over 50 other languages,including Catalan,Chinese,Dutch,Finnish,French,German,Italian'''
result={}
#a中单词之间既有空格的也有','的，第一步先以空格为维度切割后继续用','进行字符串拼接
b=','.join(a.split(' '))
#第二步继续使用',为维度进行切割，对生成的列表进行去重操作'
new=set(b.split(','))
#循环新的列表
for i in new:
#在之前新建了一个空字典，循环过程中，取每个单词作为字典键值，去重后的每个单词在原列表中的个数当作value值，对字典进行赋值，目前字典中存储了每个单词在a中出现次数
    result[i]=a.count(i)
#使用sortde函数和lambda函数对字典进行降序排列，排序后是是个列表，按照索引方式取列表前5项内容，然后继续把列表转字典
print(dict(sorted(result.items(),key=lambda x:x[-1],reverse=True)[0:5]))
#通过以上几个步骤就实现了统计一篇英文文章每个单词的出现频率，并返回出现频率最高的前5个单词及其出现次数(字典形式)




lists=[]
lists1=[]
result={}
a='A small sample of texts from Project Gutenberg appears in the NLTK corpus collection. However, you may be interested in analyzing other texts from Project Gutenberg. You can browse the catalog of 25,000 free online books at http://www.gutenberg.org/catalog/, and obtain a URL to an ASCII text file. Although 90% of the texts in Project Gutenberg are in English, it includes material in over 50 other languages, including Catalan, Chinese, Dutch, Finnish, French, German, Italian'
for j in a.split(' '):
    if j.isalpha():
        lists.append(j)
    elif j.endswith(',') and j[0:-1].isalpha():
        lists.append(j[0:-1])
lists_set=list(set(lists))
for i in lists_set:
    lists1.append((lists.count(i),i))
lists1=sorted(lists1,reverse=True)[0:5]
for i in range(0,len(lists1)):
    result[lists1[i][1]]=lists1[i][0]
print(result)






# 练习57：
# a={"business_autoFans_J": [{"2016_08":14}, {"2016_09":15}, {"2016_10":9}],"autoAX": [{"2016_08":7}, {"2016_09":32}, {"2016_10":0}],"autoAX_admin": [{"2016_08":5}, {"2016_09":13}, {"2016_10":2}]}
# m=9
# bugs=0
# for v in a.values():
#     for i in v:
#         if list(i.keys())[0].endswith(str(m)):
#             bugs+=list(i.values())[0]
# print(bugs)


# 练习58：
# a={ '001':{'name':"李四",'age':28,'address':"山东",'score':88},
#     '002':{'name':"张三",'age':18,'address':"北京",'score':98},
#     '003':{'name':"小明",'age':48,'address':"河北",'score':90},
#     '004':{'name':"王五",'age':38,'address':"北京",'score':78}
# }
# maxage=0
# maxname=''
# for v in a.values():
#     if v['address']!='北京':
#         v['score']+=10
#     if  v['age']>maxage:
#         maxage=v['age']
#         maxname=v['name']
# print(maxname)
# print(a)

# 练习59：
# list1=[]
# list1.append(1)
# list1.append(2)
# list1.pop(0)
# if len(list1):
#     print(list1)
# else:
#     exit

# 练习61：
# def my_funtion(list):
#         if len(list) > 5:
#             print('输入长度不能大于5')
#         else:
#             print(list)
# my_funtion([1,2,3])
# my_funtion((1,2,3,4))
# my_funtion('1234')
# my_funtion([1,2,3,6,8,9])

# 练习62：
# def my_test(str):
#     count1={}
#     dight,aha,space,othrer=0,0,0,0
#     for j in str:
#         if j.isdigit():
#             dight+=1
#         elif j.isalpha():
#             aha+=1
#         elif j.isspace():
#             space+=1
#         else:
#             othrer+=1
#         count1['dight']=dight
#         count1['aha'] = aha
#         count1['space'] = space
#         count1['othrer'] = othrer
#     print(count1)
# my_test('234rrr **')
# 练习63：
#
# def creaturl(hostname,**kwargs):
#     a=[]
#     if kwargs['url'] and kwargs['data']:
#        for k,v in kwargs['data'].items():
#            a.append('{k}={v}'.format(k=k,v=v))
#        print(f'http://{hostname}/' + kwargs['url']+'/' + '&'.join(a))
# creaturl(hostname='172.20.223.201', url='path', data={'a': 1, 'b': 2})
# 练习64：
# def collatz(number):
#     if number==1:
#         print('over')
#         return 1
#     elif number%2==0:
#         print(number // 2)
#     elif number%2!=0:
#         print(number*3+1)
# while True:
#     n=int(input('请输入一个整数'))
#     if collatz(n)==1:
#         break
# 练习65：

import random

# # 随机数函数
# def random_number():
#     return random.random()
# # 统计奖项函数
# def count_number(i):
#     if i>=0 and i<0.08:
#         a = 1
#     elif i >=0.08 and i<0.3:
#         a = 2
#     else:
#         a = 3
#     return a
# #主函数
# def tongji(count):
#     one = 0
#     two = 0
#     three = 0
#     for i in range(0, count):
#         i = random_number()
#         level = count_number(i)
#         if level == 1:
#             one+=1
#         elif level == 2:
#             two+=1
#         elif level == 3:
#             three+=1
#     return [one, two, three]
# print(tongji(1000))

# 练习66：
# def make_shirt(size,content):
#     if size=='s':
#         s='小'
#     elif size=='m':
#         s='中'
#     elif size=='l':
#         s='大'
#     print(f'T恤的尺码为{s}，字样为{content}')
# make_shirt('s','I love China')


# def make_shirt1(size='大号',content='I love Python'):
#     print(f'T恤的尺码为{size}，字样为{content}')
# make_shirt1()
# make_shirt1('中号')
# make_shirt1('小号','I love java')
# 练习67：
#定义一个变量，取当前时间时间
# times=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
# #定义一个函数，有默认值的参数放到后边，不定长参数处理：**kwargs（参数当字典处理，传参格式是a='b',a是key，'b'是value），如果是*args把参与的参数当作列表处理
# def sayWhat(city,age,content,name='匿名',**kwargs):
# #字符串拼接
#     print('来自[{name}]{times}的留言:{content}'.format(name=name,times=times,content=content))
#     print('-----------------------------------')
# #判断kwargs字典根据key为'zan'和'pinglun'有值，get方法获取不到不报错
#     if kwargs.get('zan') and kwargs.get('pinglun'):
#         print('、'.join( kwargs.get('zan'))+'赞过')
#         print('')
#         print(kwargs.get('pinglun'))
#         print('')
#     else:
#         print('')
# sayWhat(city='北京',age=18,content='刘老师最帅',name='张三',zan=['李四','王二'],pinglun='[张老师]评论：说的好')
# sayWhat(city='北京',age=18,content='中国最帅',name='李四')

# 练习68：

# def my_function():
#     shuzi = []
#     card=[]
#     for i in range(2,11):
#         shuzi.append(i)
#     shuzi.extend(["J", "Q", "K", "A"])
#     for i in shuzi:
#         for j in  ["黑桃", "红桃", "方块", "草花"]:
#             card.append((j,i))
#     print(card)
# res=my_function()





# 练习69：
# a=['adam','LISA','barT']
# print(list(map(lambda x:x.lower().capitalize(),a)))
#循环列表a然后先转小写，再首字母转大写
# a=['adam','LISA','barT']
# b=[]
# for i in a:
#     b.append(i.lower().capitalize())
# print(b)
# 练习70：
# a=[]
# for i in range(1,1001):
#     a.append(i)
# print(list(filter(lambda x:str(x)==str(x)[::-1],a)))

# data= [["liulaoshi","18","学习"],["tom", 25, "无"],["hanmeimei", 26, "花钱"]]
# print(list(filter(lambda x:x[-1]!="无",data)))
# data= [["liulaoshi","18","学习"],["tom", 25, "无"],["hanmeimei", 26, "花钱"]]
# def my_function(x):
#     if x[-1]=='无':
#         return False
#     else:
#         return True
# print(list(filter(my_function,data)))
#
# print(list(filter(lambda x:x[-1]!="无",data)))
# 练习71：
# a=[1,3,5,7,9]
# print(reduce(lambda x,y:x+y,a))
#
# a=[1,3,5,7,9]
# print(reduce(lambda x,y:x*10+y,a))

# 练习72：



# L =[('Bob',75), ('Adam',92), ('Bart',66), ('Lisa',88)]
# # 定义第一个函数返回L每个元组的倒数第一项
# def my_function1(x):
#     return x[-1]
# # 定义第2个函数返回L每个元组的第一项
# def my_function2(x):
#     return x[0]
# #调用第一个函数对成绩进行倒叙排列
# a=sorted(L,key=my_function1,reverse=True)
# #调用第二个函数对数据进行操作，只保留第一项数据转列表输出
# print(list(map(my_function2,a)))
#
# #不定义函数，直接调用lambda函数操作
# print(list(map(lambda y:y[0],sorted(L,key=lambda x:x[-1],reverse=True))))
# 练习73：


# 练习77&78：
# class Student():
#     count=0
#     school='中国Python职业技术学院'
#     def __init__(self,id,name,age,score=None):
#         self.id = id
#         self.name = name
#         self.age = age
#         self.score = score
#         Student.count+=1
#     def introduce(self):
#         print(f'我叫{self.name},今年{self.age}')
#         print(f'{Student.school}-{self.id}-{self.name}')
#     def get_age(self):
#         print(self.age)
#     def set_age(self):
#         self.newage=19
#         print(f'更新为最新年龄为{self.newage}')
#     @classmethod
#     def sing(cls):
#         print(f'我为{Student.school}10岁生日献歌')
#     def how_many(self):
#         print(self.count)
# def hello_my_school(student):
#     print(f'我是{student.name}我爱我的母校{student.school}')
# a=Student('01','张三',18,19)
# b=Student('02','李四',20,21)
# c=Student('02','李四',20,21)
# a.introduce()
# a.get_age()
# a.set_age()
# a.sing()
# a.how_many()
# hello_my_school(a)

# 练习79：
#第一种实现方式

#-----------------------------
# class Connection:
#     def __init__(self,host='172.20.223.201',port='9081',db=''
#                                                            'da',charset='utf-8',password='123456'):
#         self.host=host
#         self.port=port
#         self.db=db
#         self.charset=charset
#         self.password=password
#     def connect(self):
#         conn = connect(self.host, self.port, self.db, self.charset, self.password)
#         return conn
#     def exc1(self,sql):
#         res=self.connect()
#         if not res:
#             return False
#         else:
#             conn.execute(sql)
#             return 'xxxx'
#     def exc2(self,name):
#         res=self.connect()
#         if not res:
#             return False
#         else:
#             conn.call_porc(name)
#             return 'xxxx'
# c=Connection()
# c.exc1('select * from student')
# c.exc2('my_pro')


#第二种实现方式
# class Connection:
#     def __init__(self,host='172.20.223.201',port='9081',db='da',charset='utf-8',password='123456'):
#         self.host=host
#         self.port=port
#         self.db=db
#         self.charset=charset
#         self.password=password
#     def exc1(self,sql):
#         conn=connect(self.host,self.port,self.db,self.charset,self.password)
#         conn.execute(sql)
#         return 'xxxx'
#
#     def exc2(self,name):
#         conn = connect(self.host, self.port, self.db, self.charset, self.password)
#         conn.call_porc(name)
#         return 'xxxx'
# c=Connection()
# c.exc1('select * from student')
# c.exc2('my_pro')

# 练习80：
# class stack():
#     def __init__(self,maxs):
#         self.maxs=maxs
#         self.li=[]
#     def empety(self):
#         if len(self.li)==0:
#             return True
#         else:
#             return False
#     def full(self):
#         if len(self.li)==self.maxs:
#             return True
#         else:
#             return False
#     def  pop(self):
#         if not self.empety():
#             self.li.pop()
#         else:
#             return None
#     def appen(self,value):
#         if not self.full():
#             self.li.append(value)
#         else:
#             print('栈已满')
#     def get_full(self):
#         print(self.maxs)
#         print(self.li)
# s=stack(3)
# s.appen(1)
# s.appen(2)
# s.appen(3)
# s.get_full()



# 练习81：
# class ComputerShop():
#     def __init__(self,product_list=None):
#         self.money=0
#         self.count=32
#         if product_list:
#             self.product_list=product_list
#         else:
#             product_list=[]
#     def serch(self,brand):
#         self.brand=brand
#         for p in self.product_list:
#             if p.get('brand')==self.brand:
#                 return p
#         else:
#             return None
#
#     def sale(self, brand):
#         p=self.serch(brand)
#         if p:
#             if p.get('count')>=1:
#                 price=p.get('price')
#                 self.money+=price
#                 p['count']= p['count']-1
#                 return self.money
#             else:
#                 print('库中不足')
#         else:
#             print('没有找到指定商品')
#     def jinhuo(self,brand):
#         p=self.serch(brand)
#         if p:
#             price=p.get('price')
#             self.money-=price-1000
#             p['count'] = p['count'] +1
#             return self.money
#
# list1 = ComputerShop([{'count':11,'brand':'拯救者','price':5999},{'count':21,'brand':'外星人','price':7999}])
# print(list1.serch('拯救者'))
# print(list1.sale('拯救者'))
# print(list1.jinhuo('外星人'))


# 练习89（捕获异常处理）：
# a=1
# b=0
# try:
#     a/b
# except:
#     print('时间 Error 错误message')

# 练习90（上抛异常）：
# try:
#     a=int(input('请输入数字a'))
#     b =int(input('请输入数字b'))
#     print(c=a-b)
# except:
#     print('被减数不能小于减数')
# finally:
#     print('该方法运行结束')

# 练习91
# import os
# def read_file(filename):
#     try:
#         file=open(filename)
#     except Exception as E:
#         print('出错了出错内容是{}'.format(E))
#     else:
#         print(file.read())
#         file.close()
# read_file('hhaha.txt')

# 练习92&93：
# import random
# num = random.randint(0,100)
# print('随机数为{num}'.format(num=num))
# while True:
#         try:
#             guess = int(input("请输入一个1~100的随机数:"))
#         except ValueError as err:
#                 print("请输入整数", err)
#         except EOFError:
#             print('00000')
#         except KeyboardInterrupt:
#             print('0--3')
#             continue
#         if guess > num:
#                 print("%d 大于随机数"  %(guess))
#         elif guess < num:
#                 print("%d 小于随机数" %(guess))
#         else:
#                 print("等于随机数,游戏结束")
#                 break
#         print("\n")
# 练习94
# info=['http://www.baidu.com','http:///www.sina.com','http://xxxx.cm']
# def get_page(listindex):
#     try:
#         listindex = int(listindex)
#         print(info[listindex])
#     except:
#         print('请输入正确的索引地址')
# get_page(2)
# get_page('t')
# get_page(5)

# 练习95：
# dict={'login.py': 'a 8 d 2 u 3 ', 'order.py': 'a 15 d 0 u 34', 'info.py': 'a 1 d 20 u 5 '}
# for k,v in dict.items():
#     #定义一个sum用来计数
#     sum = 0
#     #循环字段中,value用空格切割后值
#     for i in v.split(' '):
#         #try一个情况，如果i能转为int就说明i是数字
#        try:
#            sum+=int(i)
#        except:
#            pass
#         #打印最后统计后的数值
#     print('文件{k}，共变更{sum}'.format(k=k,sum=sum))
# 练习96:

# try:
#     #time.strptime,把制定格式的日期字符串转为日期元组，如果可以转就说明输入日期格式正确，无法正确转就说明输入日期与约定格式不一致，Try的妙用
#     time.strptime('2019-11-18 17:00:00','%Y-%m-%d %H:%M:%S')
#     print('输入时间格式字符串符合指定格式')
# except:
#     print('输入格式错误')

# 练习97:
# #先把指定格式日期字符串转为元组，time.mktime把元组转为日期时间戳
times=time.mktime(time.strptime('2017-10-10 23:40:00','%Y-%m-%d %H:%M:%S'))
#日期时间戳转为日期元组，按照指定格式转为日期字符串
print(time.strftime('%Y/%m/%d %H:%M:%S',time.localtime(times)))

# 练习98:
#先获取当前时间戳，time.time,距离1970.1.1过去了多少秒，减去三天一共计算出秒数，算出当前时间往前推三天时间戳，转为时间元组，拼接为指定日期格式日期字符串
# print(time.strftime('%Y-%m-%d_%H:%M:%S',time.localtime(time.time()-24*3*60*60)))
# 练习99:
#定义一个函数接收一个列表
# def Time(list):
#     #通过"."对列表完成字符串拼接
#     times_a = '.'.join(list)
#     #将拼接后指定格式的日期字符串，转为时间元组，继续转为时间戳
#     d = time.mktime(time.strptime(times_a, '%Y.%m.%d'))
#     #将'1970.1.2'转为时间元组继续转为时间戳
#     c = time.mktime(time.strptime('1970.1.2', '%Y.%m.%d'))
#     #调用一个random.uniform（所及生成一个指定范围内的符点数），参数为时间戳上限和下限
#     times = random.uniform(c, d)
#     #将随机生成的时间戳，转为时间元组，继续拼接为指定格式字符串
#     print(time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime(times)))
#     #函数调用
# Time(['2017','01','15'])

# 练习2
# def Time(str):
#     #把指定格式日期 字符串转为元组，继续转为时间戳
#     times1=time.mktime(time.strptime(str,'%H:%M:%S_%m/%d/%Y'))
#     #把上一步转的时间戳，转为日期元组，继续拼接为指定格式日期字符串
#     times2=time.strftime('%Y-%m-%d_%H:%M:%S',time.localtime(times1))
#     print(times2)
# Time('13:28:06_12/21/2018')
